package com.example.community.rest;

import com.example.community.dto.AdminDto;
import com.example.community.dto.DeleteDto;
import com.example.community.mapper.AdminMapper;
import com.example.community.model.Admin;
import com.example.community.model.AdminExample;
import com.example.community.service.CommentService;
import com.example.community.service.QuestionService;
import com.example.community.util.CookieChecking;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("admin")
public class AdminResource {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private CommentService commentService;

    @PostMapping("/login")
    public Integer login(@RequestBody AdminDto adminDto, HttpServletResponse response){
        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria().andAccountEqualTo(adminDto.getAccount())
                .andPasswordEqualTo(adminDto.getPassword());
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size() != 0){
            String token = UUID.randomUUID().toString();
            Admin admin = new Admin();
            admin.setToken(token);
            adminMapper.updateByExampleSelective(admin,adminExample);
            Cookie cookie = new Cookie("AMtoken", "AM" + token);
            cookie.setMaxAge(60 * 60 * 24 * 15);
            cookie.setPath("/");
            response.addCookie(cookie);
        }else {
            return 2;
        }
        return 1;
    }

    @PostMapping("delete")
    public Integer delete(@RequestBody DeleteDto deleteDto, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = CookieChecking.CookieToken(cookies,"AMtoken");
        if (token != null){
            if (deleteDto.getType().equals("question")){
                boolean deleteQuestionSuccess = questionService.deleteQuestion(deleteDto.getId());
                if (!deleteQuestionSuccess){
                    return 2;
                }
            }else if (deleteDto.getType().equals("comment")){
                boolean deleteCommentSuccess = commentService.deleteComment(deleteDto.getId());
                if (!deleteCommentSuccess){
                    return 2;
                }
            }
        }else {
            return 3;
        }
        return 1;
    }
}
